﻿using System;
using System.Windows.Input;

namespace InterfaceWeaver.AopCore
{
    public class CommandMapper<T>: ICommand
    {
        private readonly Action<T> executeAction = null;
        private readonly Func<T, bool> canExecuteAction = null;

        /// <summary>
        /// Initializes a new instance of the <see cref="CommandMapper" /> class.
        /// </summary>
        /// <param name="executeAction">The execute action.</param>
        /// <param name="canExecuteAction">The can execute action.</param>
        public CommandMapper(Action<T> executeAction, Func<T, bool> canExecuteAction)
        {
            this.executeAction = executeAction;
            this.canExecuteAction = canExecuteAction;
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="CommandMapper" /> class.
        /// </summary>
        /// <param name="executeAction">The execute action.</param>
        public CommandMapper(Action<T> executeAction)
            : this(executeAction, null) { }

        /// <summary>
        /// Defines the method that determines whether the command can execute in its current state.
        /// </summary>
        /// <param name="parameter">Data used by the command.  If the command does not require data to be passed, this object can be set to null.</param>
        /// <returns>
        /// true if this command can be executed; otherwise, false.
        /// </returns>
        public bool CanExecute(object parameter)
        {
            return this.canExecuteAction == null || this.canExecuteAction((T)parameter);
        }

        /// <summary>
        /// Defines the method to be called when the command is invoked.
        /// </summary>
        /// <param name="parameter">Data used by the command.  If the command does not require data to be passed, this object can be set to null.</param>
        public void Execute(object parameter)
        {
            if(this.executeAction != null)
            {
                this.executeAction((T)parameter);
            }
        }

        /// <summary>
        /// Occurs when changes occur that affect whether or not the command should execute.
        /// </summary>
        public event EventHandler CanExecuteChanged
        {
            add { CommandManager.RequerySuggested += value; }
            remove { CommandManager.RequerySuggested -= value; }
        }
    }
}
